<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>流程步骤定义列表</title>
    <link rel="stylesheet" type="text/css" href="${params.contextPath}/static/plug/ztree/css/zTreeStyle/zTreeStyle.css"/>
	<#include "/common/resource.ftl">
    <script type="text/javascript" src="${params.contextPath}/static/js/jquery-ui.js?_t=${params.pageRandom!}"></script>
    <script type="text/javascript" src="${params.contextPath}/static/plug/ztree/js/jquery.ztree.all.min.js"></script>
    <script type="text/javascript" src="${params.contextPath}/static/js/jquery-ui.js"></script>
    <style>
        .step-num{background:#FF5722;color:#fff;border-radius:50%;height:25px;width:25px;line-height:26px;text-align:center;}
        .user-item{display:inline-block;background:#5FB878;color:#fff;border-radius:5px;line-height:30px;padding:0px 10px;margin-right:10px;margin-bottom:10px;}
        .layui-btn-xs{font-size:12px !important;}
        .show-users{color:#1E9FFF;cursor:pointer;}
        .user-dialog{padding:10px;}
        .step-list{padding:0px;padding-top:1px;background:#eee;}
        .step-item{background:#fff;padding:10px;margin-top:5px;}
    </style>
</head>
<body style="background:#eee">

<div class="layui-container" style="padding:10px 0px;">
    <div class="layui-row" style="background:#fff;padding:10px;margin-bottom:10px;">
        <div class="layui-col-md10" style="color:#FFB800;line-height:28px;">
            1 拖动步骤条目即可排序；2 所有的操作必须在保存之后才会生效
        </div>
        <div class="layui-col-md2" style="text-align:right;">
            <input type="button" value="保存" class="layui-btn submit-button" />
        </div>
    </div>
    <div class="layui-row layui-col-space10">
        <div class="layui-col-md6">
            <div class="layui-card">
                <div class="layui-card-header">编辑步骤</div>
                <div class="layui-card-body">
                    <form class="layui-form step-form" action="${params.contextPath}/web/workflowStep/save" method="post">
                        <div class="layui-form-item">
                            <label class="layui-form-label">名称<span class="ui-request">*</span></label>
                            <div class="layui-input-block">
                                <input type="text" data-name="name" placeholder="请输入名称" class="layui-input {required:true}"/>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">执行人<span class="ui-request">*</span></label>
                            <div class="layui-input-block ui-more-parent">
                                <ul id="user-tree" class="ztree"></ul>
                                <#--<input type="text" data-user-name="userName" placeholder="请输入执行人" p="model:'user',handlerId:'user_step_id_handler_select'" class="layui-input single-model-select {required:true}" readonly/>
                                <input type="hidden" data-user-id="userId"/>-->
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <input type="button" value="添加" class="layui-btn add-button" />
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <div class="layui-col-md6">
            <div class="layui-card">
                <div class="layui-card-header">步骤排序</div>
                <div class="layui-card-body step-list"></div>
            </div>
        </div>
    </div>
</div>
<script id="step-template" type="text/html" style="display: none">
    {{ each list item index }}
    <div class="layui-row step-item">
        <div class="layui-col-md10">
            {{item.name}}（<span class="show-users">查看执行人</span>）
            <input type="hidden" name="workflowDefineId" value="${params.workflowDefineId!}"/>
            <input type="hidden" name="users" value="{{item.users}}"/>
            <input type="hidden" name="stepNum" value="{{item.stepNum || ''}}"/>
            <input type="hidden" name="id" value="{{item.id || ''}}"/>
            <input type="hidden" name="name" value="{{item.name || ''}}"/>
        </div>
        <div class="layui-col-md1">
            <div class="step-num">{{item.stepNum || '--'}}</div>
        </div>
        <div class="layui-col-md1" style="text-align:right;">
            <#--<input type="button" value="修改" class="layui-btn layui-btn-xs  modify-button" />-->
            <input type="button" value="删除" class="layui-btn layui-btn-xs layui-btn-normal remove-button" />
        </div>
    </div>
    {{ /each }}
</script>
<script type="text/javascript">
    var setting = {
        check: {enable: true, chkboxType: {"Y": "ps", "N": "ps"}},
        data: {simpleData: {enable: true}},
        //callback: {}
    };

    var initTree = function () {
        $.ajaxRequest({
            url:"${params.contextPath}/web/user/userOrgTree",
            success:function (data) {
                if (!data.success) {
                    $.message(data.message);
                    return;
                }
                var zTree = $.fn.zTree.init($("#user-tree"), setting, data.data);
                var nodes = zTree.transformToArray(zTree.getNodes());
                zTree.expandNode(nodes[0], true);
            }
        });
    };

    var initData = function () {
        $.ajaxRequest({
            url:"${params.contextPath}/web/workflowStep/list",
            data:{workflowDefineId:'${params.workflowDefineId!}'},
            success:function (data) {
                if (!data.success) {
                    $.message(data.message);
                    return;
                }
                var list = data.data;
                for (var i = 0; i < list.length; i++) {
                    var item = list[i];
                    item.users = JSON.stringify(item.userList);
                }
                var html = $.template("step-template", {list: list});
                $(".step-list").html(html);
                setStepNum();
                initTree();
            }
        });
    };

    //获取选中的用户账号
    var getCheckUsers = function () {
        var zTree = $.fn.zTree.getZTreeObj("user-tree");
        var checkeds = zTree.getCheckedNodes();
        var userArray = new Array();
        for (var i = 0; i < checkeds.length; i++) {
            var item = checkeds[i];
            if (!item.isUser) {
                continue;
            }
            userArray.push({userId: item.id, userName: item.name});
        }
        return userArray;
    };

    //按照指定长度为数字前面补零
    var numFormat = function(num, length) {
        return (Array(length).join('0') + num).slice(-length);
    };

    //设置排序号
    var setStepNum = function() {
        $(".step-list .layui-row").each(function (index) {
            var num = numFormat(index + 1, 2);
            $(this).find('[name="stepNum"]').val(index + 1);
            $(this).find('.step-num').html(num);
        });
    };

    $(function () {
        LocalStorage.registHandler("user_step_id_handler_select", function (data) {
            $('input[data-user-id="userId"]').val(data.id);
            $('input[data-user-name="userName"]').html(data.name);
        });

        initData();

        $(".add-button").click(function () {
            var name = $('[data-name="name"]').val();
            var users = getCheckUsers();
            if (!name) {
                $.message("名称为空");
                return;
            }
            if (!users || users.length <= 0) {
                $.message("请选择执行人");
                return;
            }
            var item = {name: name, users: JSON.stringify(users)};

            var dataArray = [];
            dataArray.push(item);
            var html = $.template("step-template", {list: dataArray});
            $(".step-list").append(html);
            setStepNum();

            //清空
            $('[data-name="name"]').val("");
            var treeObj = $.fn.zTree.getZTreeObj("user-tree");
            treeObj.checkAllNodes(false);
        });

        $(".step-list").on("click", ".show-users", function () {
            var arr = $(this).parent().find('[name="users"]').val();
            arr = JSON.parse(arr);
            var str = '<ul class="user-dialog">';
            for (var i = 0; i < arr.length; i++) {
                var item = arr[i];
                str += '<li class="user-item">{0}</li>'.format(item.userName);
            }
            str += "<ul>";
            layer.open({
                type: 1,
                title: '用户信息',
                area: ['420px', '240px'],
                content: str
            });
        });

        $(".step-list").sortable({
            cursor: "move",
            items: ".step-item",
            opacity: 0.6,
            revert: true,
            update: function (event, ui) {
                setStepNum();
            }
        });

        $(".step-list").on("click", ".remove-button", function () {
            var obj = $(this);
            var alt = layer.alert("确定删除该步骤吗？", function () {
                obj.parent().parent().remove();
                setStepNum();
                layer.close(alt);
            });
        });

        $(".submit-button").click(function () {
            var items = [], errMsg = "";
            $(".step-list .step-item").each(function (index) {
                var workflowDefineId = $(this).find("[name='workflowDefineId']").val();
                if (!workflowDefineId) {
                    errMsg = "未选择所属流程，无法保存";
                    return false;
                }
                var workflowDefineId = $(this).find("[name='workflowDefineId']").val();
                var users = $(this).find("[name='users']").val();
                var stepNum = $(this).find("[name='stepNum']").val();
                var id = $(this).find("[name='id']").val() || "";
                var name = $(this).find("[name='name']").val() || "";

                var userArr = JSON.parse(users), userIds = [];
                for (var i = 0; i < userArr.length; i++) {
                    userIds.push(userArr[i].userId);
                }

                items.push({
                    workflowDefineId: workflowDefineId,
                    stepNum: stepNum,
                    id: id,
                    name: name,
                    userIds: userIds
                });
            });
            if (errMsg) {
                $.message(errMsg);
                return;
            }

            $.ajaxRequest({
                url: "${params.contextPath}/web/workflowStep/save",
                data: {items: JSON.stringify(items)},
                success: function (data) {
                    if (!data.success) {
                        $.message(data.message);
                        return;
                    }
                    var alt = layer.alert(data.message, function () {
                        parent.layer.closeAll();
                        layer.close(alt);
                    });
                }
            });
        });
    });
</script>
</body>

</html>
